package com.xb.testdown.update;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.xb.testdown.update.bean.UpdateInfo;
import com.xb.testdown.update.http.RetrofitServiceFactory;
import com.xb.testdown.update.http.UpdateService;

import java.io.File;
import java.io.IOException;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 检查更新类，还需要写接口回调
 */
public class UpdateCheckUtil {

    //下载器
    private DownloadManager downloadManager;
    //下载的ID
    private long downloadId;
    private String pathstr;
    private Context mContext;
    private String mApkName;
    private String mDownUrl;

    public UpdateCheckUtil(Context context, String DownUrl, String ApkName) {
        mContext = context;
        this.mDownUrl = DownUrl;
        this.mApkName = ApkName;
    }

    /**
     * 检查更新
     * 无需传参数直接检查： 需要检查 app 的版本号
     */
    @SuppressWarnings("unused")
    public static void checkUpdate(UpdateCallback updateCallback) {
        UpdateService updateService = RetrofitServiceFactory.createServiceFrom(UpdateService.class, UpdateService.base_url);

        /*updateService.getUpdateInfo("", "").enqueue(new Callback<Response>() {
            @Override
            public void onResponse(Call<Response> call, Response<Response> response) {

            }

            @Override
            public void onFailure(Call<Response> call, Throwable t) {

            }
        });*/


        updateService.getUpdateInfo1("flfwdy.lawdoo.com")
                .subscribeOn(Schedulers.newThread()) // 订阅：指定Observable自身在哪个调度器上执行
                .observeOn(AndroidSchedulers.mainThread()) // observeOn 指定最后结果在哪个线程 观察：指定一个观察者在哪个调度器上观察这个Observable
                .subscribe(updateInfo -> onNext(updateInfo, updateCallback),
                        throwable -> onError(throwable, updateCallback));


    }

    private static void onNext(UpdateInfo updateInfo, UpdateCallback updateCallback) {
        // 判断返回的信息是否成功不成功就弹出错误回调
        if (1 == 1) {
            updateCallback.onError();
        } else {
            updateCallback.onSuccess(updateInfo);
        }
    }

    private static void onError(Throwable throwable, UpdateCallback updateCallback) {
        updateCallback.onError();

    }

    // 更新回调
    public interface UpdateCallback {
        void onSuccess(UpdateInfo updateInfo);

        void onError();
    }

    // 下载文件
    public void downloadApk() {

        // 下载地址
        if (mDownUrl.isEmpty() || mDownUrl == null) {
            Toast.makeText(mContext, "下载地址为空，请联系管理员", Toast.LENGTH_SHORT).show();
            return;
        }

        //创建下载任务
        DownloadManager.Request request;
        try {
            request = new DownloadManager.Request(Uri.parse(mDownUrl));
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        //移动网络情况下是否允许漫游
        request.setAllowedOverRoaming(false);
        //在通知栏中显示，默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle("版本更新");
        request.setDescription("该版本有更新，更新的内容如下");
        request.setVisibleInDownloadsUi(true); // 设置是否必须手机处于空闲状态下载，默认否

        // 版本大于 3
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            request.allowScanningByMediaScanner(); // 可以被扫描到
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); // 设置可见
        }
        //设置下载的路径
        File file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), mApkName);
        request.setDestinationUri(Uri.fromFile(file));
        pathstr = file.getAbsolutePath();

        // 获取DownloadManager
        //获取DownloadManager
        if (downloadManager == null)
            downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        //将下载请求加入下载队列，加入下载队列后会给该任务返回一个long型的id，通过该id可以取消任务，重启任务、获取下载的文件等等
        if (downloadManager != null) {
            downloadId = downloadManager.enqueue(request);
        }


        //注册广播接收者，监听下载状态
        mContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));


    }

    public BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkStatus();
        }
    };

    //检查下载状态
    public void checkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        //通过下载的id查找
        query.setFilterById(downloadId);
        Cursor cursor = downloadManager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {

                //下载暂停
                case DownloadManager.STATUS_PAUSED:
                    break;
                //下载延迟
                case DownloadManager.STATUS_PENDING:
                    break;
                //正在下载
                case DownloadManager.STATUS_RUNNING:
                    break;
                //下载完成
                case DownloadManager.STATUS_SUCCESSFUL:
                    //下载完成安装APK
                    installAPK();
                    cursor.close();
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
                    cursor.close();
                    mContext.unregisterReceiver(receiver);
                    break;
            }

        }

    }

    public void installAPK() {
        setPermission(pathstr);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //Android 7.0以上要使用FileProvider
        if (Build.VERSION.SDK_INT >= 24) {
            File file = (new File(pathstr));
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(mContext, "com.lxtwsw.weather.fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");

        } else {
            intent.setDataAndType(Uri.fromFile(new File(Environment.DIRECTORY_DOWNLOADS, mApkName)), "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);

    }

    //修改文件权限
    private void setPermission(String absolutePath) {
        String command = "chmod " + "777" + " " + absolutePath;
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec(command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
